package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class Base extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        System.out.println("BASE start");
        String methodname=req.getParameter("method");//当前的参数值恰好是方法名 reg/login
        if (methodname == null) {
            methodname = "all";
        }
        Class c=this.getClass();
        try {
            Method m=c.getDeclaredMethod(methodname,HttpServletRequest.class,HttpServletResponse.class);
            Object obj=m.invoke(this,req,resp);
            if(obj!=null&&obj instanceof String){
                String url=(String)obj;
                if(url.startsWith("z:")){
                req.getRequestDispatcher(url.substring(2)).forward(req,resp);
                }else if(url.startsWith("r:")){
                   resp.sendRedirect(url.substring(2));
                }else{
                    PrintWriter pw=resp.getWriter();
                    pw.write(url);
                    pw.flush();
                    pw.close();
                }
            }
            System.out.println("base...end"+new Date());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
